from typing import Any, Sequence

from fastmcp import FastMCP
from sqlalchemy import create_engine, text, Result, Row
from sqlalchemy.orm import sessionmaker

DB_CONFIG = {
    "host": "129.204.145.139:3306",
    "user": "root",
    "password": "SS#202411#1859",
    "database": "fintax_analysis_dev",
    "charset": "utf8mb4"
}
MYSQL_URL = "mysql+aiomysql://root:123456@127.0.0.1/fin_tax_analysis?charset=utf8mb4"

engine = create_engine(
    MYSQL_URL,
    pool_size=20,  # 连接池大小
    max_overflow=10,  # 最大溢出连接数
    pool_recycle=3600,  # 连接回收时间(秒)
    pool_pre_ping=True,  # 执行前健康检查
    echo=True,  # SQL日志
)
# 2. 创建会话工厂，并把当前引擎绑定给该对话
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False, expire_on_commit=True)
dbClient = SessionLocal()

mcp = FastMCP("Predefined SQL Query Service")

@mcp.tool()
def get_last_month_order_count() :
    """查询上个月的订单总数"""
    sql = """
        SELECT COUNT(*) FROM orders WHERE DATE_FORMAT(created_at, '%Y-%m') = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m')
    """
    result = dbClient.execute(text(sql))
    return result.scalar()


# 启动
if __name__ == "__main__":
    mcp.run(transport="streamable-http", port=8090, path="/mcp")